package com.liuceng.mps.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CoeUtils {

  public static Double getMajorCof(double realCost, String rangeMark, String values) {
    if (StringUtils.isBlank(rangeMark)) {
      String[] valsArr1 = values.split(",");

      if (valsArr1 == null || valsArr1.length != 2) {
        return 0.0;
      }
      return Double.parseDouble(realCost > 0 ? valsArr1[1] : valsArr1[0]);
    }
    //
    String[] marksArr = rangeMark.split(",");
    List<Integer> marks =
        marksArr != null && marksArr.length > 0 ? Arrays.asList(marksArr).stream()
            .map(e -> Integer.parseInt(e)).collect(Collectors.toList()) : new ArrayList<>();
    // ///
    String[] valsArr = values.split(",");
    List<Double> vals =
        valsArr != null && valsArr.length > 0 ? Arrays.asList(valsArr).stream()
            .map(e -> Double.parseDouble(e)).collect(Collectors.toList()) : new ArrayList<>();
    // 当均客资成本等于0 的时候
    if (realCost == 0) {
      return vals != null && vals.size() > 0 ? vals.get(0) : 1.0;
    }

    // 移除第零位的数据--及均客资成本为0 的时候的系数
    if (vals != null && vals.size() > 0) {
      vals.remove(0);
    }
    if (marks.size() * 2 + 1 != vals.size()) {
      return 1.0;
    }
    //
    return vals.get(binarySearch(realCost, marks.toArray(new Integer[marks.size()])));
  }

  private static int binarySearch(double cost, Integer[] number) {
    int low = 0;
    int upper = number.length - 1;
    while (low <= upper) {
      int mid = (low + upper) / 2;
      if (number[mid] < cost) {
        low = mid + 1;
      } else if (number[mid] > cost) {
        upper = mid - 1;
      } else {
        return mid * 2 + 1;
      }
    }

    if (number.length == 0)
      return 0;
    if (number.length <= low)
      return number.length * 2;
    if (number[low] > cost) {
      return low * 2;
    } else if (number[low] < cost) {
      return low * 2 + 2;
    }

    return -1;
  }
}
